import React, {useEffect, useState} from 'react'
import {useHistory, useModel} from 'umi'
import {Button, Form, Input, message, Upload, Row, Col} from 'antd'
import {FileOutlined} from '@ant-design/icons'
import type {UploadProps} from 'antd/es/upload/interface'
import {modalApi} from '@/utils/modalReq'
import styles from './index.less'
import {
	templateconfigList,
	templateconfigSave,
	templateconfigUpdate,
} from '@/service/system/templateMaintenance'

const editors = (props: any) => {
	const {query} = props.location || {}
	const [form] = Form.useForm()
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const history: any = useHistory()
	const [giftNamespace, setgiftNamespace] = useState<any>()
	const [detailsData, setDetailsData] = useState<any>()

	useEffect(() => {
		if (query?.id) {
			templateconfigList({id: query?.id}).then((res: any) => {
				if (res?.success) {
					const newData = res?.data?.records?.[0]
					setDetailsData(newData)
					setgiftNamespace(newData?.fileName)
					form?.setFieldsValue({
						company: query?.company,
						templateType: newData?.templateType,
						upData: {
							file: {
								uid: '-1',
								name: newData?.fileName,
								url: newData?.url,
								response: {
									data: {
										filename: newData?.fileName,
										url: newData?.url,
										giftNamespace: newData?.giftNamespace,
										id: newData?.giftId,
									},
								},
							},
							fileList: [
								{
									uid: '-1',
									name: newData?.fileName,
									status: 'done',
									url: newData?.url,
									response: {
										data: {
											filename: newData?.fileName,
											url: newData?.url,
											giftNamespace:
												newData?.giftNamespace,
											id: newData?.giftId,
										},
									},
								},
							],
						},
					})
				}
			})
		} else {
			form?.setFieldsValue({
				company: query?.company,
			})
		}
	}, [query])

	const onFinish = (value: any) => {
		const values = value
		values.id = query?.id
		values.giftNamespace =
			values.upData?.file?.response?.data?.giftNamespace
		values.giftId = `${values.upData?.file?.response?.data?.id}`
		delete values.upData

		delete values.company
		let request
		if (query?.id) {
			delete values.templateType
			request = templateconfigUpdate(values)
		} else {
			request = templateconfigSave(values)
		}
		request
			.then((res: any) => {
				if (res?.success) {
					message.success('保存成功')
					history.push({
						pathname: '/systemSetup/templateMaintenanceList',
					})
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}

	const updataProps: UploadProps = {
		name: fileName,
		action: `${modalApi.common}/shopec-template-config/templateconfig/uploadFiles`,
		data: {
			modelName: detailsData?.modelName || '',
			targetAttr: 0,
		},
		maxCount: 1,
		showUploadList: false,
		onChange(info) {
			const name = info?.file.name
			form?.setFieldsValue({
				templateType: name?.substring(0, name?.lastIndexOf('.')),
			})
			if (info.file.status === 'done') {
				message.success(`${info.file.name} 上传成功`)
				setgiftNamespace(info.file.name)
			} else if (info.file.status === 'error') {
				message.error(`${info.file.name} 上传失败`)
			}
		},
	}

	return (
		<div className={styles.content}>
			<Form
				form={form}
				name="basic"
				onFinish={onFinish}
				autoComplete="off"
				layout="horizontal"
				labelCol={{flex: '140px'}}
				labelAlign="right"
				labelWrap>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item label="所属公司" name="company">
							<Input disabled />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item label="模板类型" name="templateType">
							<Input
								placeholder="根据上传模板名称回填"
								disabled
							/>
						</Form.Item>
					</Col>
					<Col span={12} style={{marginRight: '10px'}}>
						<Form.Item
							label="上传模板"
							name="upData"
							rules={[
								{
									required: true,
									message: '请上传模板',
								},
							]}
							help={
								<div>
									<p>附件说明：附件最大支持50M</p>
								</div>
							}>
							<Upload {...updataProps}>
								<Row>
									{giftNamespace ? (
										<Col>
											<div className={styles.fileName}>
												<FileOutlined
													style={{fontSize: '14px'}}
												/>
												<span>{giftNamespace}</span>
											</div>
										</Col>
									) : (
										<></>
									)}
									<Col>
										<Button type="link">
											{giftNamespace
												? '重新上传'
												: '上传'}
										</Button>
									</Col>
								</Row>
							</Upload>
						</Form.Item>
					</Col>
				</Row>
				<Form.Item>
					<div className={styles.btns}>
						<Button type="primary" htmlType="submit">
							保存
						</Button>
						<Button
							style={{marginLeft: '15px'}}
							onClick={() =>
								history.push({
									pathname:
										'/systemSetup/templateMaintenanceList',
								})
							}>
							取消
						</Button>
					</div>
				</Form.Item>
			</Form>
		</div>
	)
}

export default editors
